package com.jctrip.hotel.source.xxl.atour.thread;

import com.jctrip.hotel.common.constant.RedisKeyConstant;
import com.jctrip.hotel.common.context.BeanContext;
import com.jctrip.hotel.common.util.JsonUtil;
import com.jctrip.hotel.common.util.RedisUtil;
import com.jctrip.hotel.domain.entity.HtSourceInfo;
import com.jctrip.hotel.source.service.atour.AtourService;
import com.jctrip.hotel.source.service.atour.AtourTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: zxy
 * @CreateTime: 2023-09-07 11:04
 * @Description:
 */
@Slf4j
public class SyncAtourPartRatesTaskThread implements Runnable {
    private final Integer days;
    private final List<HtSourceInfo> sourceInfos;

    public SyncAtourPartRatesTaskThread(List<HtSourceInfo> sourceInfos, Integer days) {
        this.sourceInfos = sourceInfos;
        this.days = days;
    }

    @Override
    public void run() {
        RedisUtil redisUtil = BeanContext.getApplicationContext().getBean(RedisUtil.class);
        AtourService atourService = BeanContext.getApplicationContext().getBean(AtourService.class);
        AtourTaskService atourTaskService = BeanContext.getApplicationContext().getBean(AtourTaskService.class);
        try {
            while (redisUtil.lGetListSize(RedisKeyConstant.HOTEL_MAIN_ATOUR_PART_RATES_LIST) > 0) {
                String hotelId = (String) redisUtil.rightPop(RedisKeyConstant.HOTEL_MAIN_ATOUR_PART_RATES_LIST);
                if (StringUtils.isBlank(hotelId)) {
                    continue;
                }
                Integer atourHotelId = atourService.parseHotelId(hotelId);
                Date start = new Date();
                Date end = DateUtils.addDays(start, days);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                sourceInfos.forEach(htSourceInfo -> {
                    atourTaskService.syncAtourPartRates(htSourceInfo.getSourceId(), Integer.valueOf(htSourceInfo.getSourceAppId()),
                            htSourceInfo.getSourceSecret(), atourHotelId, simpleDateFormat.format(start),
                            simpleDateFormat.format(end), (Integer) JsonUtil.toMap(htSourceInfo.getExtra()).get("mebId"));
                });
            }
        } catch (Exception e) {
            log.error("SyncAtourRatesTaskThread error", e);
        }

    }
}